import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { DatePipe } from '@angular/common';
import {Student} from '../student';
import {StudentService} from '../student.service';

@Component({
  selector: 'app-students',
  templateUrl: './students.component.html',
  styleUrls: ['./students.component.css']
})
export class StudentsComponent implements OnInit {
  reasonStudents: Array<Student> = [];
  students: Array<Student> = [];
  validateForm: FormGroup;

  datePipe: DatePipe = new DatePipe('zh-CN');

  constructor(
    private studentService: StudentService,
    private formBuilder: FormBuilder,
  ) {
    this.validateForm = this.formBuilder.group({
      major: [''],
      class: [''],
      native_place: [''],
      birthday1: [''],
      birthday2: [''],
      time_of_enrollment: [''],
    });
  }

  ngOnInit(): void {
    // @ts-ignore
    this.handleSearch();
  }


  // 表单提交
  submitForm(values) {
    console.log('values', values);
    const startBirthday = values.birthday1 ? this.formatDate(values.birthday1) : '';
    const endBirthday = values.birthday2 ? this.formatDate(values.birthday1) : '';
    const className = values.class.trim();
    const nativePlace = values.native_place.trim();

    // this.handleSearch(values);
    this.students = this.reasonStudents.filter(item => {
      const { major, native_place, birthday1, birthday2, time_of_enrollment } = values;

      // 过滤专业
      if (values.major && values.major !== item.major) {
        return false;
      }

      // 过滤班级
      // if (values.class && values.class !== item.class) {
      //   return false;
      // }
      if (item.class.trim().indexOf(className) === -1) {
        return false;
      }

      // 过滤籍贯
      if (item.native_place.trim().indexOf(nativePlace) === -1) {
        return false;
      }

      // 出生年月
      const birthday = this.formatDate(item.birthday);
      if ((startBirthday && startBirthday > birthday) || (endBirthday && endBirthday < birthday)) {
        return false;
      }

      // 入学年份
      if (values.time_of_enrollment && values.time_of_enrollment !== item.time_of_enrollment) {
        return false;
      }

      return true;
    });
  }

  // 重置查询条件
  resetForm($event: MouseEvent) {
    this.handleSearch(null);
  }

  // 查询
  handleSearch(params) {
    this.studentService.getStudents(params).subscribe((data: any) => {
      console.log('getStudents', data)
      if (data.status === 1) {
        this.students = data.data;
        this.reasonStudents = JSON.parse(JSON.stringify(this.students));
      }
    });
  }

  // 格式化时间
  formatDate(date: string | Date): string {
    return this.datePipe.transform(date, 'YYYY/MM');
  }
}

